#include <func.h>

int main(int argc, char* argv[])
{
    // 客户端
    // 确定服务器希望通信的方式
    struct addrinfo hints;
    bzero(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = 0;

    struct addrinfo* result;
    int err = getaddrinfo("127.0.0.1", "9527", &hints, &result);
    if (err) {
        fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(err));
        exit(1);
    }  // IPv4, IPv6, UDP, TCP 

    // 创建客户端的通信端点 (主动套接字)
    int sockfd = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    printf("INFO: sockfd=%d\n", sockfd);

    // 发送连接请求
    err = connect(sockfd, result->ai_addr, result->ai_addrlen);
    if (err) {
        error(1, errno, "connect()");
    }
    printf("INFO: 三次握手成功\n");
    
    char request[] = "GET /index.html HTTP/1.1\r\n\r\n";    // HTTP请求信息
    send(sockfd, request, strlen(request), 0);            // 写入发送缓冲区

    // 接收数据
    char buf[4096] = {'\0'};
    int n = recv(sockfd, buf, 4096, 0);
    if (n > 0) {
        puts(buf);
    }

    // 关闭连接
    close(sockfd);
    return 0;
}

